package com.suxin.rpc;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.nio.charset.Charset;

/**
 * @author Tang
 * @classname NettyServerHandler
 * @description [ TODO ]
 * @date 2021/1/17 19:29
 */
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("server channelActive...");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("server--->channelRead");

        String msgString = msg.toString();
        System.out.println("server--->" + msgString);
        if (msgString.startsWith("HelloService#hello")) {
            int index = msgString.lastIndexOf("#") + 1;
            HelloServiceImpl helloService = new HelloServiceImpl();
            ctx.channel().writeAndFlush(
                    Unpooled.copiedBuffer(
                            helloService.hello(msgString.substring(index))
                            , Charset.defaultCharset()
                    )
            );
        }

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
        cause.printStackTrace();
    }
}